package com.ujiuye.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 该servlet主要用于被其他自定义Servlet 继承
 */
//@WebServlet("*.do")
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 处理post请求乱码
        req.setCharacterEncoding("UTF-8");
// 响应给浏览器数据乱码处理
        resp.setContentType("text/html;charset=utf-8");
// 获取请求的统一资源定位符
        String uri = req.getRequestURI();
        System.out.println("uri = " + uri);
// 截取每次请求路径不同的部分
        String method = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf(".do"));
        System.out.println(method);
// 通过反射实现方法的调用
// 1. 获取当前类的类对象
        Class<? extends BaseServlet> aClass = this.getClass();
// 2. 获取当前类的 public方法对象
        try {
            Method meth = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
//this.add(req,resp);
// 3. 反射实现方法的调用
            meth.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
////        System.out.println("add 方法被执行了");
//    }

}
